//
//  AccountCenterViewController.m
//  SP2P
//
//  Created by EIMS-IOS on 16/1/12.
//  Copyright (c) 2016年 EIMS. All rights reserved.
//

#import "AccountCenterViewController.h"
#import "UIViewController+NavBar.h"
#import "MyAccountNavBar.h"
#import "TradeRecordViewController.h"
#import "AboutUSViewController.h"
#import "SecurityViewController.h"
#import "MailViewController.h"
#import "MyBankCardViewController.h"
#import "AddBankCardViewController.h"
#import "ExperienceViewController.h"
#import "BillManagerViewController.h"
#import "SQBProfitViewController.h"
#import "SQBRechargeViewController.h"
#import "SQBWithdrawViewController.h"
#import "CacheUtil.h"
#import "SGLoginViewController.h"
#import "GesDatabase.h"
#import "AccountCenterCell.h"
#import "ChangeMobileViewController.h"
#import "VerifyMobileViewController.h"
#import "SetPayPasswordViewController.h"
#import "RechargeQuestionViewController.h"

@interface AccountCenterViewController ()<UITableViewDelegate,UITableViewDataSource,HTTPClientDelegate,UIAlertViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
{
    UILabel *_availableAmountLabel;
    UILabel *_sqbAmountLabel;
    UILabel *_investPlanLabel;
    ClickButton *_rechargeButton;
    ClickButton *_withdrawButton;
    UILabel *_totalPropertyLabel;
}
@property (nonatomic, strong) UIView  *headerView;
@property (nonatomic, strong) MyAccountNavBar *navBarView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *imageDataArray;
@property (nonatomic, strong) NSMutableArray *detailDataArray;
@property (nonatomic, strong) UIView *footerView;

@property (nonatomic ,strong) NetWorkClient *requestClient;
@property (nonatomic, copy  ) NSString      *cacheFileName;
@property (nonatomic, assign) BOOL           isLoading;
@property (nonatomic, assign) NSInteger      requestType;
@end

@implementation AccountCenterViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    self.navigationController.navigationBarHidden = YES;

    if (AppDelegateInstance.userInfo) {
        _tableView.tableFooterView = _footerView;
        [self setUserInfo];
        [self headerRereshing];
    }else {
        _tableView.tableFooterView = nil;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self resetNavigationBar];
    self.navigationController.navigationBarHidden = NO;
    
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = KbackgroundColor;
    [self initNaviBar];
    
    [self initData];
    [self initView];
    
}

#pragma mark - Action
- (void)withdrawButtonClick {
    if ([self realNameInfoVerify] == NO) {
        return;
    }
    if (!AppDelegateInstance.userInfo.isPayPasswordStatus) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"您尚未设置交易密码" message:@"是否前去设置交易密码？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = 15;
        [alertView show];
        return;
    }
    
    SQBWithdrawViewController *withdraw = [[SQBWithdrawViewController alloc] init];
    withdraw.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:withdraw animated:YES];
}

- (void)rechargeButtonClick {
    if ([self realNameInfoVerify] == NO) {
        return;
    }
    
    SQBRechargeViewController *recharge = [[SQBRechargeViewController alloc] init];
    recharge.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:recharge animated:YES];
}

- (BOOL)realNameInfoVerify {
    if (AppDelegateInstance.userInfo.mobile.length <= 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"您尚未绑定手机号" message:@"是否前去绑定手机号？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = 14;
        [alertView show];
        return NO;
    }
    
    if (AppDelegateInstance.userInfo.realName.length<=0 || !AppDelegateInstance.userInfo.hasBindCard || AppDelegateInstance.userInfo.mobile.length<=0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"您尚未完成实名认证信息" message:@"是否前去完善实名认证信息？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = 13;
        [alertView show];
        return NO;
    }
    
    return YES;
}

- (void)logoutButtonClick {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"退出账户" message:@"确定要退出此账户吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.tag = 12;
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==12 && buttonIndex==1) {
        // 记录 退出状态
        if (AppDelegateInstance.userInfo != nil) {
            //[[AppDefaultUtil sharedInstance] removeGesturesPasswordWithAccount: AppDelegateInstance.userInfo.userName];// 移除该账号的手势密码
        }
        //            [[AppDefaultUtil sharedInstance] setDefaultUserName:@""];// 清除用户昵称
        //            [[AppDefaultUtil sharedInstance] setDefaultUserPassword:@""];// 清除用户密码
        [[AppDefaultUtil sharedInstance] setDefaultAccount:@""];// 清除用户账号
        [[AppDefaultUtil sharedInstance] setDefaultHeaderImageUrl:@""];// 清除用户头像
        
        AppDelegateInstance.userInfo = nil;
        AppDelegateInstance.userInfo.isLogin = 0;
        
        SGLoginViewController *loginVC = [[SGLoginViewController alloc] init];
        loginVC.backType = SecuritySet;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self.navigationController presentViewController:navigationController animated:YES completion:nil];
    }else if (alertView.tag==13 && buttonIndex==1) {
        AddBankCardViewController *addBankCard = [[AddBankCardViewController alloc] init];
        addBankCard.editType = 1;
        addBankCard.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:addBankCard animated:YES];
    }else if (alertView.tag==14 && buttonIndex==1) {
        ChangeMobileViewController *changeMobile = [[ChangeMobileViewController alloc] init];
        changeMobile.isChangeBank = NO;
        changeMobile.backNum = 2;
        changeMobile.naviTitle = @"绑定手机号";
        changeMobile.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:changeMobile animated:YES];
    }else if (alertView.tag==15 && buttonIndex==1) {
        //设置交易密码
        SetPayPasswordViewController *changePwd = [[SetPayPasswordViewController alloc] init];
        //changePwd.delegate = self;
        changePwd.editType = 1;
        changePwd.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:changePwd animated:YES];
    }
}

#pragma mark - TableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
        {
            SQBProfitViewController *SQBProfit = [[SQBProfitViewController alloc] init];
            SQBProfit.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:SQBProfit animated:YES];
        }
            break;
        case 1:
        {
            BillManagerViewController *billManager = [[BillManagerViewController alloc] init];
            billManager.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:billManager animated:YES];
        }
            break;
        case 2:
        {
            ExperienceViewController *experience = [[ExperienceViewController alloc] init];
            experience.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:experience animated:YES];
        }
            break;
        case 3:
        {
            if (AppDelegateInstance.userInfo.realName.length>0 && AppDelegateInstance.userInfo.hasBindCard && AppDelegateInstance.userInfo.hasRecharge) {
                //实名认证信息
                MyBankCardViewController *myBankCard = [[MyBankCardViewController alloc] init];
                myBankCard.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:myBankCard animated:YES];
            }else {
                //去实名认证
                AddBankCardViewController *addBankCard = [[AddBankCardViewController alloc] init];
                if (AppDelegateInstance.userInfo.hasBindCard) {
                    addBankCard.editType = 2;
                }else {
                    addBankCard.editType = 1;
                }
                addBankCard.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:addBankCard animated:YES];
            }
            
        }
            break;
        case 4:
        {
            SecurityViewController *security = [[SecurityViewController alloc] init];
            security.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:security animated:YES];
        }
            break;
        case 5:
        {
            RechargeQuestionViewController *rechargeQuestion = [[RechargeQuestionViewController alloc] init];
            rechargeQuestion.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:rechargeQuestion animated:YES];
        }
            break;
        case 6:
        {
            MailViewController *mail = [[MailViewController alloc] init];
            mail.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mail animated:YES];
        }
            break;
        case 7:
        {
            AboutUSViewController *aboutUs = [[AboutUSViewController alloc] init];
            aboutUs.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:aboutUs animated:YES];
        }
            break;
            
        default:
            break;
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    AccountCenterCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"AccountCenterCell" owner:self options:nil][0];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    }
    cell.leftImageView.image = [UIImage imageNamed:_imageDataArray[indexPath.row]];
    cell.titleLabel.text = _dataArray[indexPath.row];
    
    NSString *detailStr = _detailDataArray[indexPath.row];
    if (detailStr.length > 0) {
        cell.detailLabel.hidden = NO;
        cell.detailLabel.text = detailStr;
    }else {
        cell.detailLabel.hidden = YES;
        cell.detailLabel.text = @"";
    }
    
    cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, KAdaptNum(44));
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0f;
}

#pragma mark - Data
- (void)initData {
    
    _dataArray = [NSMutableArray array];
    _imageDataArray = [NSMutableArray array];
    _detailDataArray = [NSMutableArray array];
    
    [_dataArray addObjectsFromArray:@[@"随取宝",@"理财计划",@"新手体验",@"实名认证",@"安全",@"充值问题",@"站内信",@"关于我们"]];
    [_imageDataArray addObjectsFromArray:@[@"account_suiqubao",@"account_bill",@"account_experience",@"account_realname",@"account_security",@"account_security",@"account_message",@"account_aboutus"]];
    [_detailDataArray addObjectsFromArray:@[@"",@"",@"",@"",@"",@"",@"",@""]];
    
}

// 请求数据
- (void)requestData {
    if (_isLoading) {
        DLOG(@"账户中心正在请求...");
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"509" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
    
    _cacheFileName = [CacheUtil creatCacheFileName:parameters];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma - HTTPClientDelegate 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
}

// 返回成功
-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    [self processData:obj isCache:NO];// 读取当前请求到的数据
}

- (void)processData:(NSDictionary *)dataDics isCache:(BOOL) isCache {
    DLOG(@"dataDics is %@",dataDics);
    if ([[NSString stringWithFormat:@"%@",[dataDics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if(!isCache){
            // 非缓存数据，且返回的是-1 成功的数据，才更新数据源，否则不保存
            NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
            NSString *cachePath = [path stringByAppendingPathComponent:_cacheFileName];// 合成归档保存的完整路径
            [NSKeyedArchiver archiveRootObject:dataDics toFile:cachePath];// 数据归档，存取缓存
        }
        
        NSString *account = [CommonClass formatConversion:[[dataDics objectForKey:@"account"] doubleValue] type:0]; //总资产
        _totalPropertyLabel.attributedText = [MyTools getNSMutableAttributedStringWithText:account start:account.length-3 end:account.length textColor:[UIColor whiteColor] textFont:KFontSize(15)];
        
        NSString *balance = [CommonClass unitConversion:[[dataDics objectForKey:@"balance"] doubleValue]];     //可用余额
        NSString *sqbAmount = [CommonClass unitConversion:[[dataDics objectForKey:@"balance3"] doubleValue]];   //随取宝
        NSString *investPlan = [CommonClass unitConversion:[[dataDics objectForKey:@"planamount"] doubleValue]];   //理财计划
    
        _availableAmountLabel.text = balance;
        _sqbAmountLabel.text = sqbAmount;
        _investPlanLabel.text = investPlan;
        
        NSString *rateStr = [NSString stringWithFormat:@"%.1f%%活期收益",[dataDics[@"apr"] floatValue]];
        [_detailDataArray replaceObjectAtIndex:0 withObject:rateStr];
        
        double unamount = [[dataDics objectForKey:@"unamount"] doubleValue]; //未使用体验金
        //double doamount = [[dataDics objectForKey:@"doamount"] doubleValue]; //已使用体验金
        NSString *unamountStr = [NSString stringWithFormat:@"%.0f元",unamount];
        if (unamount <= 0) {
            unamountStr = @"已体验";
        }
        [_detailDataArray replaceObjectAtIndex:2 withObject:unamountStr];
        
        if (AppDelegateInstance.userInfo.realName.length<=0 || !AppDelegateInstance.userInfo.hasBindCard) {
            NSString *realNameVerifyStaus = @"未认证";
            [_detailDataArray replaceObjectAtIndex:3 withObject:realNameVerifyStaus];
        }else {
            NSString *realNameVerifyStaus = @"已认证";
            [_detailDataArray replaceObjectAtIndex:3 withObject:realNameVerifyStaus];
        }
        
        NSInteger securityMark = 20;
        if (AppDelegateInstance.userInfo.isMobileStatus) {
            securityMark += 20;
        }
        if (AppDelegateInstance.userInfo.isEmailStatus) {
            securityMark += 20;
        }
        if (AppDelegateInstance.userInfo.isPayPasswordStatus) {
            securityMark += 20;
        }
        //是否开启手势密码
        NSString *accountStr = [[AppDefaultUtil sharedInstance] getDefaultAccount];
        NSString *gestureState=[[GesDatabase getInstance] getGestureState:accountStr];
        if ([gestureState isEqualToString:@"1"]) {
            securityMark += 20;
        }
        NSString *securityLevelStr = @"";
        if (securityMark < 60) {
            securityLevelStr = @"低";
        }else if (securityMark>=60 && securityMark<80) {
            securityLevelStr = @"中";
        }else {
            securityLevelStr = @"高";
        }
        [_detailDataArray replaceObjectAtIndex:4 withObject:securityLevelStr];
        
        //未读消息数
        NSInteger unReadMsgCount = [[dataDics objectForKey:@"unReadMsgCount"] integerValue];
        NSString *unReadMsgCountStr = @"";
        if (unReadMsgCount > 0) {
            unReadMsgCountStr = [NSString stringWithFormat:@"%@条未读",[dataDics objectForKey:@"unReadMsgCount"]];
        }
        [_detailDataArray replaceObjectAtIndex:6 withObject:unReadMsgCountStr];
        
        
        if (!isCache) {
            // 非缓存数据才显示隐藏
            [self hiddenRefreshView];
        }
        
        [_tableView reloadData];
        
    }else {
        if (!isCache) {
            // 非缓存数据才显示错误
            [self hiddenRefreshView];
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [dataDics objectForKey:@"msg"]]];
        }
    }
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    [self hiddenRefreshView];
    [self readCache];
}

// 无可用的网络
- (void)networkError {
    _isLoading = NO;
    [self hiddenRefreshView];
    [self readCache];
}

#pragma 加载缓存数据
-(void) readCache {
    // 刷新前先加载缓存数据
    NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cachePath = [path stringByAppendingPathComponent:_cacheFileName];// 合成归档保存的完整路径
    NSDictionary *dics = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];// 上一次缓存数据
    [self processData:dics isCache:YES];// 读取上一次成功缓存的数据
}

- (void)setUserInfo {
    if (AppDelegateInstance.userInfo) {
        if (AppDelegateInstance.userInfo.realName.length > 0) {
            NSString *realName = AppDelegateInstance.userInfo.realName;
            NSInteger suffLength = 0;
            if (realName.length > 2) {
                suffLength = 1;
            }
            _navBarView.usernameLabel.text = [NSString stringWithFormat:@"%@*%@",[realName substringToIndex:1],[realName substringFromIndex:realName.length-suffLength]];
        }else {
            _navBarView.usernameLabel.text = [CommonClass getAsteriskUserName];
        }
        [_navBarView.headerImageView sd_setImageWithURL:[NSURL URLWithString:AppDelegateInstance.userInfo.userImg] placeholderImage:KDefaultHead];
    }
}

#pragma mark - 更换头像
- (void)dealHeaderTap {
    DLOG(@"上传图片按钮");
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    [actionSheet addButtonWithTitle:@"拍照"];
    [actionSheet addButtonWithTitle:@"从手机相册选择"];
    //[actionSheet addButtonWithTitle:@"取消"];
    actionSheet.destructiveButtonIndex = actionSheet.numberOfButtons - 1;
    [actionSheet showInView:self.view];
}


#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.editing = YES;
    imagePicker.allowsEditing = YES;
    imagePicker.delegate = self;
    
    if (buttonIndex == 1)//照相机
    {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePicker animated:YES completion:nil];
            
        }
        else{
            
            [SVProgressHUD showErrorWithStatus:@"该设备没有摄像头"];
            
        }
    }else if (buttonIndex == 2)
    {
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    
}

#pragma mark - UIImagePicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(saveImage:) withObject:image afterDelay:0.5];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)saveImage:(UIImage *)image {
    _navBarView.headerImageView.image = image;
    
    [self uploadHeaderImageWithImage:image];
}

- (void)uploadHeaderImageWithImage:(UIImage *)image {
    
    if (image!= nil) {
        
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
        [parameters setObject:@"1" forKey:@"type"];
        
        // 1. Create `AFHTTPRequestSerializer` which will create your request.
        AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
        
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        
        //    NSString *restUrl = [ShoveGeneralRestGateway buildUrl:@"/app/services" key:MD5key parameters:parameters];
        //
        //    DLOG(@">>>>>>>>>URL>>>>>>%@<<<<<<<", [NSString stringWithFormat:@"%@%@", Baseurl, restUrl]);
        
        
        // 2. Create an `NSMutableURLRequest`.
        
        NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",Baseurl,@"/app/uploadUserPhoto"]
                                                                       parameters:parameters
                                                        constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                                            
                                                            
                                                            //上传时使用当前的系统事件作为文件名
                                                            
                                                            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                                                            
                                                            formatter.dateFormat = @"yyyyMMddHHmmss";
                                                            
                                                            NSString *str = [formatter stringFromDate:[NSDate date]];
                                                            
                                                            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
                                                            //
                                                            
                                                            
                                                            [formData appendPartWithFileData:imageData
                                                                                        name:@"imgFile"
                                                                                    fileName:fileName
                                                                                    mimeType:@"image/jpeg"];
                                                        } error:nil];
        
        // 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
        DLOG(@">>>>>>>>request>>>>>>%@<<<<<<<", request);
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        AFHTTPRequestOperation *operation =
        [manager HTTPRequestOperationWithRequest:request
                                         success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                             DLOG(@"Success >>>>>>>>>>>>>>>>>%@", responseObject);
                                             NSDictionary *dic = (NSDictionary *)responseObject;
                                             if([[dic objectForKey:@"error"] integerValue] == -1)
                                             {
                                                 [SVProgressHUD showSuccessWithStatus:[dic objectForKey:@"msg"]];
                                                 if ([[dic objectForKey:@"filename"] hasPrefix:@"http"]) {
                                                     AppDelegateInstance.userInfo.userImg =[NSString stringWithFormat:@"%@",[dic objectForKey:@"filename"]] ;
                                                     [[AppDefaultUtil sharedInstance] setDefaultHeaderImageUrl:[NSString stringWithFormat:@"%@", [dic objectForKey:@"filename"]]];
                                                 }else
                                                 {
                                                     
                                                     AppDelegateInstance.userInfo.userImg =[NSString stringWithFormat:@"%@%@", Baseurl, [dic objectForKey:@"filename"]] ;
                                                     [[AppDefaultUtil sharedInstance] setDefaultHeaderImageUrl:[NSString stringWithFormat:@"%@%@", Baseurl, [dic objectForKey:@"filename"]]];
                                                 }
                                                 
                                                 [[NSNotificationCenter defaultCenter]  postNotificationName:@"updateHeaderIcon" object:nil];
                                                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * 600000000ull)), dispatch_get_main_queue(), ^{
                                                     
                                                     
                                                     [self.navigationController popViewControllerAnimated:YES];
                                                     
                                                 });
                                                 
                                             }else{
                                                 
                                                 
                                                 [SVProgressHUD showErrorWithStatus:[dic objectForKey:@"msg"]];
                                                 
                                                 
                                             }
                                             
                                             
                                             
                                             
                                         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                            // DLOG(@"Failure >>>>>>>>>>>>>>>>>%@", error.description);
                                         }];
        
        // 4. Set the progress block of the operation.
        [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                            long long totalBytesWritten,
                                            long long totalBytesExpectedToWrite) {
            //DLOG(@"Wrote >>>>>>>>>>>>>>>>>%lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
        }];
        
        // 5. Begin!
        [operation start];
        //DLOG(@">>>>>>>>>>>>>>>END<<<<<<<<<<<<<<<<<");
        
    }
    
}


#pragma mark - 刷新
- (void)headerRereshing {
    [self requestData];
}

- (void)footerRereshing {
    [self requestData];
}

- (void)hiddenRefreshView {
    if (!_tableView.mj_header.hidden) {
        [_tableView.mj_header endRefreshing];
    }
    if (!_tableView.mj_footer.hidden) {
        [_tableView.mj_footer endRefreshing];
    }
}



#pragma mark - View
- (void)initView {
    
    self.edgesForExtendedLayout = UIRectEdgeNone;


    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.estimatedRowHeight = KAdaptNum(44.0);
    _tableView.frame = RECTMAKE(0, 0, MSWIDTH, MSHIGHT - 49);

    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    _tableView.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    
    // 自动刷新(一进入程序就下拉刷新)
    //    [self.tableView headerBeginRefreshing];
    
    [self loadHeadView];
    [self loadFooterView];
    
}

- (void)loadFooterView {
    _footerView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, KAdaptNum(55)) backgroundColor:KbackgroundColor superview:nil];
    
    UIButton *logoutButton = [UIButton buttonWithFrame:RECTMAKE(0, 0, MSWIDTH, GetHeight(_footerView) - 10) backgroundColor:[UIColor whiteColor] title:@"退出登录" titleColor:KGrayColor titleFont:14 target:self action:@selector(logoutButtonClick) superview:_footerView];
    logoutButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    
}

// 初始化导航栏
- (void)loadHeadView {
    self.navigationController.navigationBar.userInteractionEnabled = YES;
    
    _headerView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, KAdaptNum(220 + 60)) backgroundColor:nil superview:nil];

    UIImageView *backImageView = [UIImageView imageViewWithFrame:RECTMAKE(0, 0, MSWIDTH, KAdaptNum(220)) imageFile:@"account_back" superview:_headerView];
    backImageView.userInteractionEnabled = YES;
    
    _navBarView = [[MyAccountNavBar alloc] initWithFrame:CGRectMake(0, KAdaptNum(20), MSWIDTH, KAdaptNum(44))];
    [_navBarView.backView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dealHeaderTap)]];
    [_navBarView.billButton addTarget:self action:@selector(tradeRecordClick) forControlEvents:UIControlEventTouchUpInside];
    [_navBarView.headerImageView setImage:KDefaultHead];
    //self.navigationItem.titleView = _navBarView;
    [_headerView addSubview:_navBarView];
    
    [self setUserInfo];
    
    UILabel *totalPropertyValue = [UILabel labelWithFrame:RECTMAKE(10, KAdaptNum(80), MSWIDTH - 20, KAdaptNum(20)) text:@"总资产(元)" textColor:[UIColor whiteColor] textFont:12 fitWidth:NO superview:backImageView];
    totalPropertyValue.textAlignment = NSTextAlignmentCenter;
    
    _totalPropertyLabel = [UILabel labelWithFrame:RECTMAKE(10, GetMaxY(totalPropertyValue) + KAdaptNum(10), MSWIDTH - 20, KAdaptNum(40)) text:@"0.00" textColor:[UIColor whiteColor] textFont:36 fitWidth:YES superview:backImageView];
    _totalPropertyLabel.textAlignment = NSTextAlignmentCenter;
    
    _withdrawButton = [[ClickButton alloc] initWithFrame:RECTMAKE(10, GetHeight(backImageView) - KAdaptNum(10) - KAdaptNum(36), (MSWIDTH - 40)/2, KAdaptNum(36))];
    [_withdrawButton setBackColor:KWithdrawButtonNormalColor HighlightColor:KWithdrawButtonNormalColor];
    [_withdrawButton setTitle:@"提现" forState:UIControlStateNormal];
    [_withdrawButton addTarget:self action:@selector(withdrawButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [backImageView addSubview:_withdrawButton];
    
    _rechargeButton = [[ClickButton alloc] initWithFrame:RECTMAKE(GetMaxX(_withdrawButton) + 20, GetMinY(_withdrawButton), (MSWIDTH - 40)/2, GetHeight(_withdrawButton))];
    [_rechargeButton setBackColor:KRechargeButtonNormalColor HighlightColor:KRechargeButtonNormalColor];
    [_rechargeButton setTitle:@"充值" forState:UIControlStateNormal];
    [_rechargeButton addTarget:self action:@selector(rechargeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [backImageView addSubview:_rechargeButton];
    
    UIView *bottomView = [UIView viewWithFrame:RECTMAKE(0, GetMaxY(backImageView), MSWIDTH, KAdaptNum(60)) backgroundColor:[UIColor whiteColor] superview:_headerView];
    
    NSArray *titleArr = @[@"可用余额(元)",@"随取宝(元)",@"理财计划(元)"];
    for (NSInteger i=0; i < titleArr.count; i++) {
        UILabel *value = [UILabel labelWithFrame:RECTMAKE(MSWIDTH/3*i + 5, KAdaptNum(10), MSWIDTH/3 - 10, KAdaptNum(20)) text:titleArr[i] textColor:KGrayColor textFont:12 fitWidth:YES superview:bottomView];
        value.textAlignment = NSTextAlignmentCenter;
        
        UILabel *label = [UILabel labelWithFrame:RECTMAKE(GetMinX(value), GetMaxY(value), GetWidth(value), KAdaptNum(20)) text:@"" textColor:KBlackColor textFont:14 fitWidth:YES superview:bottomView];
        label.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            _availableAmountLabel = label;
        }else if (i == 1) {
            _sqbAmountLabel = label;
        }else if (i == 2) {
            _investPlanLabel = label;
        }
        
        if (i < titleArr.count-1) {
            [UIView viewWithFrame:RECTMAKE(MSWIDTH/3* (i+1), KAdaptNum(10), 1, GetHeight(bottomView) - KAdaptNum(20)) backgroundColor:KlayerBorder superview:bottomView];
        }
    }
    
    _tableView.tableHeaderView = _headerView;
    
    
}

- (void)tradeRecordClick {
    TradeRecordViewController *tradeRecord = [[TradeRecordViewController alloc] init];
    tradeRecord.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:tradeRecord animated:YES];
}

- (void)initNaviBar {
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
